<template>
    <div class="common-container">
        <el-row class="top-actions" :gutter="10">
            <el-col :span="12" class="left-actions">
                <el-button type="success" @click="handleAdd">
                    <el-icon>
                        <Plus />
                    </el-icon>新增
                </el-button>
            </el-col>
            <el-col :span="12" class="right-actions">
                <el-button type="default" @click="handleRefresh">
                    <el-icon>
                        <Refresh />
                    </el-icon>
                    刷新
                </el-button>
            </el-col>
        </el-row>
        <div class="table-scroll-container">
            <el-table :data="tableData" stripe border style="width: 100%" v-loading="loading">
                <el-table-column prop="month" label="月份" />
                <el-table-column prop="price" label="单价" />
                <el-table-column label="操作" width="100">
                    <template #default="scope">
                        <el-button size="small" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600px" :before-close="handleDialogClose"
            :close-on-click-modal="false">
            <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px">
                <el-row :gutter="20">
                    <el-col :span="11">
                        <el-form-item label="月份" prop="month">
                            <el-date-picker v-model="formData.month" type="month" placeholder="请选择月份"
                                :disabled="isEditMode" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="11">
                        <el-form-item label="单价" prop="price">
                            <el-input-number v-model="formData.price" :controls="false" :min="0">
                                <template #prefix>
                                    <span>￥</span>
                                </template>
                            </el-input-number>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <el-button @click="handleDialogClose">取消</el-button>
                <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确定</el-button>
            </template>
        </el-dialog>
        <div class="pagination-container">
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                :current-page="currentPage" :page-sizes="[15, 30, 45, 60, 100]" :page-size="pageSize"
                layout="total, sizes, prev, pager, next, jumper" :total="total" />
        </div>
    </div>
</template>
<script setup>
import { ref, onMounted, nextTick } from 'vue';
import { Plus, Refresh } from '@element-plus/icons-vue';
import { formatDate } from '@/utils/Format.js';
import { errorNotify } from '@/utils/Misc';
import htglAPI from '@/api/htgl';
const tableData = ref([]);
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(15);
const total = ref(0);
const dialogVisible = ref(false);
const dialogTitle = ref('');
const isEditMode = ref(false);
const formRef = ref(null);
const formData = ref({
    id: null,
    month: new Date(),
    price: 0,
});
const priceDecimalPlaces = ref(0);
const formRules = ref({
    month: [
        { required: true, message: '请选择日期', trigger: 'blur' }
    ],
    price: [
        { required: true, message: '请输入电价', trigger: 'change' },
        { type: 'number', min: 0.01, message: '电价必须大于0', trigger: 'change' }
    ]
});
const submitLoading = ref(false);
const getDecimalPlaces = (num) => {
    if (typeof num !== 'number') {
        num = parseFloat(num);
    }
    if (Number.isInteger(num)) {
        return 0;
    }
    const parts = num.toString().split('.');
    return parts.length > 1 ? parts[1].length : 0;
};
const fetchData = () => {
    loading.value = true;
    const params = {
        pageDto: {
            pageNo: currentPage.value,
            pageSize: pageSize.value,
            orderBy: 'month desc'
        },
    };
    htglAPI.listDianJia(params).then((res) => {
        tableData.value = res.data.page.list || [];
        tableData.value.forEach((item) => {
            item.month = formatDate(item.month, 5);
        });
        total.value = res.data?.page?.count || list.length;
        loading.value = false;
    }).catch((error) => {
        errorNotify("MeiYueDianJia.vue", "fetchData", error);
        total.value = 100;
        loading.value = false;
    });
};
onMounted(() => {
    fetchData();
});
const handleAdd = () => {
    dialogTitle.value = '添加电价';
    isEditMode.value = false;
    dialogVisible.value = true;
    nextTick(() => {
        resetFormData();
    });
};
const handleEdit = (row) => {
    dialogTitle.value = '编辑电价';
    isEditMode.value = true;
    dialogVisible.value = true;
    priceDecimalPlaces.value = getDecimalPlaces(row.price);
    nextTick(() => {
        formData.value = {
            id: row.id,
            month: row.month,
            price: row.price
        };
    });
};
const handleDialogClose = () => {
    dialogVisible.value = false;
    nextTick(() => {
        resetFormData();
    });
};
const handleSubmit = () => {
    formRef.value.validate((valid) => {
        if (valid) {
            submitLoading.value = true;
            const formDataToSubmit = {
                ...formData.value,
                month: formatDate(formData.value.month, 3)
            };
            htglAPI.saveDianJia(formDataToSubmit).then((res) => {
                submitLoading.value = false;
                handleDialogClose();
                handleRefresh();
                resetFormData();
            }).catch((error) => {
                errorNotify("MeiYueDianJia.vue", "handleSubmit", error);
                submitLoading.value = false;
            });
        } else {
            return false;
        }
    });
};
const resetFormData = () => {
    formData.value = {
        id: null,
        month: new Date(),
        price: 0,
    };
    priceDecimalPlaces.value = 0;
    if (formRef.value) {
        formRef.value.clearValidate();
    }
};
const handleRefresh = () => {
    fetchData();
};
const handleSizeChange = (val) => {
    pageSize.value = val;
    fetchData();
};
const handleCurrentChange = (val) => {
    currentPage.value = val;
    fetchData();
};
</script>
<style scoped>
.common-container {
    padding: 20px;
    background-color: #fff;
    border-radius: 4px;
    max-height: calc(100vh - 40px);
    display: flex;
    flex-direction: column;
}

.top-actions {
    margin-bottom: 20px;
    align-items: center;
}

.left-actions {
    text-align: left;
}

.right-actions {
    text-align: right;
}

.table-scroll-container {
    flex: 1;
    overflow-y: auto;
    margin-bottom: 20px;
    max-height: calc(100vh - 290px);
}

.table-scroll-container::-webkit-scrollbar {
    width: 8px;
    height: 8px;
}

.table-scroll-container::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 4px;
}

.table-scroll-container::-webkit-scrollbar-thumb {
    background: #c1c1c1;
    border-radius: 4px;
}

.table-scroll-container::-webkit-scrollbar-thumb:hover {
    background: #a8a8a8;
}

.pagination-container {
    margin-top: auto;
    padding-top: 10px;
    display: flex;
    justify-content: flex-end;
    position: sticky;
    bottom: 0;
    background-color: #fff;
    z-index: 10;
}

.preview-content {
    max-height: 400px;
    overflow-y: auto;
    padding: 10px;
}

.preview-content h4 {
    margin: 0 0 10px 0;
    color: #333;
}

.preview-content p {
    margin: 5px 0;
    font-size: 14px;
    line-height: 1.4;
    color: #666;
}

.preview-content strong {
    color: #333;
}

.upload-file {
    width: 50%;
    text-align: left;
}

.upload-file el-button {
    display: inline-block;
    margin-left: 0;
}
</style>
